package com.business.action.system;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.business.bean.system.FileBean;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import net.sf.rose.file.util.FileUtils;
import net.sf.rose.jdbc.KeyGenerator;
import net.sf.rose.util.RoseRuntimeException;
import net.sf.rose.util.StringUtil;
import sun.misc.BASE64Encoder;

/**
 * @author: fengjian
 * @date: 2018/06/28 22:30
 * @description:图片文件的上传与下载
 */
@Controller
public class UEditorAction {

    private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * ueditor控件上传图片
	 * @param url
	 * @return
	 */
	@RequestMapping("/ueditor.do")
	@ResponseBody
	public String ueditorUpload(HttpServletRequest request, String action) {
		// 获取配置信息
		if ("config".equals(action)) {
			String str = configJson.toString();
			String callbackName = request.getParameter("callback");
			return callbackName + "(" + str + ");";
		}
		// 上传图片
		else if ("uploadimage".equals(action) || "uploadscrawl".equals(action) || "uploadvideo".equals(action)
				|| "uploadfile".equals(action)) {
			
			
			
			List<FileBean> list = new ArrayList<>();
	        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			// 有图片则上传图片
			if (fileMap != null) {
				File path = FileUtils.IMAGE_PATH;
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
				String ymd = sdf.format(new Date());
				path = new File(path, ymd);
				// 创建文件夹
				if (!path.exists()) {
					path.mkdirs();
				}
				try {
					for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
						// 上传文件
						FileBean fb = new FileBean();
						MultipartFile mf = entity.getValue();
						byte[] data = mf.getBytes();
						String origName = mf.getOriginalFilename();// 获取原文件名
						String subfix = origName.substring(origName.lastIndexOf("."));
						fb.setOriginalName(origName);
						fb.setType(subfix);
						fb.setSize(data.length);
						subfix = KeyGenerator.getSystemUUID() + subfix;
						File uploadFile = new File(path, subfix);
						FileCopyUtils.copy(mf.getBytes(), uploadFile);
						System.out.println(uploadFile);
						fb.setFileName(subfix);
						fb.setUrl("/images/" + ymd + '/' + subfix);
						
						
						
						
						// savePath = /ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}.jpg
						String savePath = null;//(String) configJson.get("imagePathFormat");	
						String originFileName = mf.getOriginalFilename();// 获取原文件名
						String suffix = originFileName.substring( originFileName.lastIndexOf( "." ) ).toLowerCase();
						originFileName = originFileName.substring(0,
								originFileName.length() - suffix.length());
						savePath = savePath + suffix;
						savePath = PathFormat.parse(savePath, originFileName);
						File f = new File(FileUtils.IMAGE_PATH.getParentFile(), savePath);
						org.apache.commons.io.FileUtils.moveFile(uploadFile, f);
						System.out.println(f);
						fb.setUrl(savePath);
						fb.setFileName(f.getName());
						
						
						
						
						list.add(fb);
					}
				} catch (IOException e) {
					throw new RoseRuntimeException(e.getMessage());
				}
			}
			
			
			
			
			
			
			
			
			// List<FileBean> list = WebUtils.saveImage(request);
			FileBean fb = list.get(0);
			StringBuilder builder = new StringBuilder();
			builder.append("{");
			builder.append("\"state\": \"SUCCESS\"");
			builder.append(",\"original\": \"" + fb.getOriginalName() + "\"");
			builder.append(",\"size\": \"" + fb.getSize() + "\"");
			builder.append(",\"title\": \"" + fb.getFileName() + "\"");
			builder.append(",\"type\": \"" + fb.getType() + "\"");
			builder.append(",\"url\": \"" + fb.getUrl() + "\"");
			builder.append("}");
			System.out.println(StringUtil.toUnicode(builder.toString()));
			return StringUtil.toUnicode(builder.toString());
		} else if ("catchimage".equals(action)) {
		} else if ("listfile".equals(action) || "listimage".equals(action)) {
		}
		return null;
	}

	/**
	 * ueditor控件上传图片
	 * @param url
	 * @return
	 */
	//@RequestMapping("/ueditor/{dir}/{name}")
	public String ueditorGetImg(@PathVariable("dir") String dir,@PathVariable("name") String name) {
		File path = FileUtils.IMAGE_PATH;
		path = new File(path, dir);
		path = new File(path, name+".png");
		String imgStr = "";
		try {
			byte[] img_data = null;
			// 读取图片字节数组
			InputStream in = new FileInputStream(path);
			img_data = new byte[in.available()];
			in.read(img_data);
			in.close();
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			imgStr = encoder.encode(img_data);
		} catch (Exception e) {
			logger.error("获取图片文件时发生错误！", e);
		}
		return imgStr;
	}
	
	private static JSONObject configJson = null;
	
	public static void initial() {
		StringBuilder builder = new StringBuilder();
		try {
			InputStream i = FileUtils.getFileInputStream("config.json");
			InputStreamReader reader = new InputStreamReader(i, "UTF-8");
			BufferedReader bfReader = new BufferedReader(reader);

			String tmpContent = null;

			while ((tmpContent = bfReader.readLine()) != null) {
				builder.append(tmpContent);
			}
			bfReader.close();
			String str = builder.toString();
			// 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
			str = str.replaceAll("/\\*[\\s\\S]*?\\*/", "");
			configJson = new JSONObject(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}